package com.ratingbay.console.utils;

import java.math.BigInteger;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ratingbay.console.common.RatingBayConst;

public class CookieUtil {

	/**
	 * 删除cookie
	 * 
	 * @param request
	 * @param response
	 * @param cookieNames要删除
	 */
	public static void delCookie(HttpServletRequest request,
			HttpServletResponse response, String[] cookieNames) {
		Map<String, String> cookieMap = CookieUtil.checkCookies(request,
				cookieNames);
		CookieUtil.addCookie(response, cookieMap, 0);
	}

	public static void delCookie(HttpServletRequest request,
			HttpServletResponse response, String cookieName) {
		String[] warpcookieNames = new String[] { cookieName };
		delCookie(request, response, warpcookieNames);
	}

	/**
	 * 写cookie
	 * 
	 * @param response
	 * @param contentsMap
	 *            存放cookie的key-value映射
	 * @param maxAgeBySeconds
	 *            cookie寿命，单位为秒
	 */
	public static void addCookie(HttpServletResponse response,
			Map<String, String> contentsMap, int maxAgeBySeconds) {
		for (String cookieKey : contentsMap.keySet()) {
			Cookie cookie = new Cookie(cookieKey, contentsMap.get(cookieKey));
			//cookie.setDomain(".ratingbay.com");
			cookie.setPath("/");
			cookie.setMaxAge(maxAgeBySeconds);
			response.addCookie(cookie);
		}
	}

	/**
	 * 返回指定的cookieValue
	 * 
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String checkCookie(HttpServletRequest request,
			HttpServletResponse response, String cookieName) {
		String cookieValue = checkCookieOnly(request, response, cookieName);
		if (StringUtils.isEmpty(cookieValue)) {
			String cookieId = CookieUtil.genCookieId(request);
			if (cookieName.equals(RatingBayConst.COOKIE_ID)) {			
				addCookie(response, Collections.singletonMap(
						RatingBayConst.COOKIE_ID, cookieId), 24 * 60 * 60 * 365*2);
			}
			request.setAttribute(cookieName, cookieId);
			return cookieId;
		}
		return cookieValue;
	}
	
	public static String checkCookieOnly(HttpServletRequest request,
			HttpServletResponse response, String cookieName) {
		String cookieValue=request.getAttribute(cookieName)!=null?request.getAttribute(cookieName).toString():null;
		if(cookieValue!=null) return cookieValue;
		String[] warpContents = new String[] { cookieName };
		cookieValue = checkCookies(request, warpContents).get(cookieName);
		return cookieValue;
	}
	
	/**
	 * 检验cookie,Map中cookie存在对应的值才返回其key-value的映射
	 * 
	 * @param response
	 * @param contentsMap
	 * @param maxAgeBySeconds
	 */
	public static Map<String, String> checkCookies(HttpServletRequest request,
			String[] cookieNames) {
		Cookie[] cookies = request.getCookies();
		// 把cookie数组转换为map
		Map<String, String> cookieMap = new HashMap<String, String>();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie.getValue());
			}
		}
		// 从cookieMap中取出要查询的cookie的key-value映射
		Map<String, String> resultMap = new HashMap<String, String>();
		for (String cookieKey : cookieNames) {
			String cookieContent = cookieMap.get(cookieKey);
			// 若存在cookie值 则放回返回map中
			if (cookieContent != null) {
				resultMap.put(cookieKey, cookieContent);
			}
		}
		return resultMap;
	}

	/**
	 * 生成cookieId
	 * 
	 * @param email
	 * @return
	 */
	public static String genCookieId(String username) {
		String stringVar = Long.toString((long) (Math.random() * 10000000000L));
		byte[] byteArrayVar = new byte[stringVar.length()];
		byteArrayVar = stringVar.getBytes();
		BigInteger bigIntVar = new BigInteger(byteArrayVar);
		String cookieId =username+ Base62.encode(bigIntVar);

		return cookieId.length() >= 50 ? cookieId.substring(0, 50) : cookieId;
	}

	private static String[] ALPHABET_ARRAY = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
			"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
			
	/**
	 * 获取当前秒数
	 * @return
	 */
	private static String cookieIdPart1(){
		return Long.toHexString(System.currentTimeMillis()/1000);
	}
	/**
	 * 获取随机字母+数字
	 */
	private static String cookieIdPart2(){
		String[] results = new String[20];
		for(int i=0;i<results.length-1;i++){
			int randomNumber = (int) Math.floor((ALPHABET_ARRAY.length)*Math.random());
			results[i] = ALPHABET_ARRAY[randomNumber];
		}
		int number = (int)Math.floor(10*Math.random());
		results[results.length-1] = String.valueOf(number);
		return StringUtils.join(results);
	}
	
	/**
	 * 生成cookieId
	 * @param request
	 * @param response
	 * @return
	 */
	public static String genCookieId(HttpServletRequest request){
		StringBuffer cookieIdBuffer = new StringBuffer();
		cookieIdBuffer.append(cookieIdPart1()).append(cookieIdPart2());
		return cookieIdBuffer.toString();
	}

	public static void main(String[] args) {
		System.out.println(cookieIdPart1()+cookieIdPart2());
	}
}
